import { useState } from 'react'
import type { DecisionRecord } from '../types'
import { t, type Language } from '../i18n/translations'
import { Copy, Plus, Minus, Zap } from 'lucide-react'
import { copyWithToast } from '../lib/clipboard'

interface DecisionCardProps {
  decision: DecisionRecord
  language: Language
}

export function DecisionCard({ decision, language }: DecisionCardProps) {
  const [showInputPrompt, setShowInputPrompt] = useState(false)
  const [showCoT, setShowCoT] = useState(false)

  function getActionStyle(actionName: string) {
    if (actionName.includes('open')) {
      return { background: 'rgba(96, 165, 250, 0.1)', color: '#60a5fa' }
    }
    if (actionName.includes('close')) {
      return { background: 'rgba(14, 203, 129, 0.1)', color: '#0ECB81' }
    }
    if (actionName === 'use_tool') {
      return { background: 'rgba(168, 85, 247, 0.1)', color: '#A855F7' }
    }
    return { background: 'rgba(248, 113, 113, 0.1)', color: '#F87171' }
  }

  function getActionIcon(actionName: string) {
    if (actionName.includes('open')) return <Plus className="w-4 h-4" />
    if (actionName.includes('close')) return <Minus className="w-4 h-4" />
    if (actionName === 'use_tool') return <Zap className="w-4 h-4" />
    return <Zap className="w-4 h-4" />
  }

  return (
    <div
      className="rounded p-5 transition-all duration-300 hover:translate-y-[-2px]"
      style={{
        border: '1px solid #2B3139',
        borderLeft: decision.success
          ? '4px solid #0ECB81'
          : '4px solid #F6465D',
        background: '#1E2329',
        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.3)',
      }}
    >
      <div className="flex items-start justify-between mb-3">
        <div>
          <div className="font-semibold" style={{ color: '#EAECEF' }}>
            {t('cycle', language)} #{decision.cycle_number}
          </div>
          <div className="text-xs" style={{ color: '#848E9C' }}>
            {new Date(decision.timestamp).toLocaleString()}
          </div>
        </div>
        <div
          className="px-3 py-1 rounded text-xs font-bold"
          style={
            decision.success
              ? { background: 'rgba(14, 203, 129, 0.1)', color: '#0ECB81' }
              : { background: 'rgba(246, 70, 93, 0.1)', color: '#F6465D' }
          }
        >
          {t(decision.success ? 'success' : 'failed', language)}
        </div>
      </div>

      {decision.input_prompt && (
        <div className="mb-3">
          <button
            onClick={() => setShowInputPrompt(!showInputPrompt)}
            className="flex items-center gap-2 text-sm transition-colors"
            style={{ color: '#60a5fa' }}
          >
            <span className="font-semibold">
              📥 {t('inputPrompt', language)}
            </span>
            <span className="text-xs">
              {showInputPrompt
                ? t('collapse', language)
                : t('expand', language)}
            </span>
          </button>
          {showInputPrompt && (
            <div
              className="mt-2 rounded p-4 text-sm font-mono whitespace-pre-wrap max-h-96 overflow-y-auto"
              style={{
                background: '#0B0E11',
                border: '1px solid #2B3139',
                color: '#EAECEF',
              }}
            >
              {decision.input_prompt}
            </div>
          )}
        </div>
      )}

      {decision.cot_trace && (
        <div className="mb-3">
          <button
            onClick={() => setShowCoT(!showCoT)}
            className="flex items-center gap-2 text-sm transition-colors"
            style={{ color: '#F0B90B' }}
          >
            <span className="font-semibold">
              📤 {t('aiThinking', language)}
            </span>
            <span className="text-xs">
              {showCoT ? t('collapse', language) : t('expand', language)}
            </span>
          </button>
          {showCoT && (
            <div
              className="mt-2 rounded p-4 text-sm font-mono whitespace-pre-wrap max-h-96 overflow-y-auto"
              style={{
                background: '#0B0E11',
                border: '1px solid #2B3139',
                color: '#EAECEF',
              }}
            >
              {decision.cot_trace}
            </div>
          )}
        </div>
      )}

      {decision.decisions && decision.decisions.length > 0 && (
        <div className="space-y-3 mb-3">
          {decision.decisions.map((action, index) => (
            <div
              key={`${action.symbol}-${index}`}
              className="text-sm rounded px-3 py-3 transition-shadow hover:shadow-lg"
              style={{ background: '#0B0E11', border: '1px solid #222527' }}
            >
              <div className="flex items-center gap-3 justify-between flex-wrap">
                <div className="flex items-center gap-3 min-w-0">
                  <span
                    className="font-mono font-bold truncate"
                    style={{ color: '#EAECEF' }}
                  >
                    {action.symbol}
                  </span>
                  <span className="mr-1">{getActionIcon(action.action)}</span>
                  <span
                    className="px-2 py-0.5 rounded text-xs font-bold whitespace-nowrap"
                    style={getActionStyle(action.action)}
                  >
                    {action.action}
                  </span>
                  {action.source && (
                    <span
                      className="px-2 py-0.5 rounded text-xs font-bold whitespace-nowrap"
                      style={{
                        background: 'rgba(168, 85, 247, 0.06)',
                        color: '#A855F7',
                        border: '1px solid rgba(168,85,247,0.12)',
                      }}
                    >
                      {action.source}
                    </span>
                  )}
                  {action.price > 0 && (
                    <span
                      className="text-xs truncate"
                      style={{ color: '#848E9C' }}
                    >
                      @ ${action.price.toFixed(2)}
                    </span>
                  )}
                  {action.new_stop_loss && (
                    <span className="text-xs" style={{ color: '#F87171' }}>
                      🛑 ${action.new_stop_loss.toFixed(2)}
                    </span>
                  )}
                  {action.new_take_profit && (
                    <span className="text-xs" style={{ color: '#0ECB81' }}>
                      🎯 ${action.new_take_profit.toFixed(2)}
                    </span>
                  )}
                  {action.close_percentage && (
                    <span className="text-xs" style={{ color: '#F0B90B' }}>
                      📊 {action.close_percentage.toFixed(1)}%
                    </span>
                  )}
                  {action.quantity > 0 && (
                    <span className="text-xs" style={{ color: '#848E9C' }}>
                      {action.quantity.toFixed(4)}
                    </span>
                  )}
                </div>
                <div className="flex items-center gap-2">
                  {action.plan_id && (
                    <button
                      onClick={() => copyWithToast(action.plan_id!)}
                      className="flex items-center gap-2 px-2 py-1 rounded text-xs text-gray-300 hover:bg-[#111213] transition"
                      title={action.plan_id}
                      aria-label={`Copy Plan ${action.plan_id}`}
                    >
                      <span style={{ color: '#94a3b8' }}>
                        Plan: {action.plan_id.slice(0, 8)}
                      </span>
                      <Copy className="w-3 h-3" />
                    </button>
                  )}
                </div>
              </div>
              {action.execution_details && (
                <div
                  className="text-xs mt-2 font-mono p-2 rounded"
                  style={{ background: 'rgba(0, 0, 0, 0.2)', color: '#A855F7' }}
                >
                  🛠️ {action.execution_details}
                </div>
              )}
              {action.reasoning && (
                <div
                  className="text-xs mt-2 truncate"
                  style={{ color: '#848E9C' }}
                >
                  {action.reasoning}
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {decision.execution_log && decision.execution_log.length > 0 && (
        <div
          className="rounded p-3 text-xs font-mono space-y-1"
          style={{ background: '#0B0E11', border: '1px solid #2B3139' }}
        >
          {decision.execution_log.map((log, index) => (
            <div key={`${log}-${index}`} style={{ color: '#EAECEF' }}>
              {log}
            </div>
          ))}
        </div>
      )}

      {decision.error_message && (
        <div
          className="rounded p-3 mt-3 text-sm"
          style={{
            background: 'rgba(246, 70, 93, 0.1)',
            border: '1px solid rgba(246, 70, 93, 0.4)',
            color: '#F6465D',
          }}
        >
          ❌ {decision.error_message}
        </div>
      )}
    </div>
  )
}

export default DecisionCard
